package com.rich.dmr.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.rich.dmr.R;
import com.rich.dmr.common.RichStaggeredGridLayoutManager;
import com.rich.dmr.model.GroupModel;
import com.rich.dmr.ui.view.CommonDialog;
import com.rich.dmr.ui.view.SimpleToolbar;
import com.rich.dmr.utils.Constant;
import com.rich.dmr.utils.ConvertUtils;
import com.rich.dmr.utils.DataBaseUtils;
import com.rich.dmr.utils.Log;
import com.rich.dmr.utils.SoundPoolUtils;

import java.util.ArrayList;
import java.util.List;

import rich.dmr.DmrManager;

public class GroupContactFragment extends Fragment implements View.OnClickListener {
    private String TAG = "rich---GroupContactFragment";
    private List<GroupModel> groupModels = new ArrayList<>();
    private DmrManager dmrManager;
    private DataBaseUtils mDataBaseUtils;
    private GroupListGridAdapter adapter;
    private SharedPreferences mSp;
    private Context mContext;
    private Switch allCall;
    private SoundPoolUtils mSoundPoolUtils;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        Log.d(TAG, "onAttach");
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        mSp = mContext.getSharedPreferences(Constant.sp_key, Context.MODE_PRIVATE);
        mDataBaseUtils = DataBaseUtils.getInstance(mContext);
        mSoundPoolUtils = SoundPoolUtils.getInstance(mContext);
        groupModels.addAll(mDataBaseUtils.findGroupContact());
        dmrManager = (DmrManager) mContext.getSystemService("dmrservice");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View root = inflater.inflate(R.layout.fragment_group_contact, container, false);
        SimpleToolbar simpleToolbar = root.findViewById(R.id.group_list_tools_bar);
        simpleToolbar.setMainTitle("Group contact");
        simpleToolbar.setLeftTitleDrawable(R.mipmap.icon_left);
        simpleToolbar.setLeftTitleClickListener(this);
        simpleToolbar.setRightTitleDrawable(R.mipmap.icon_plus);
        simpleToolbar.setRightTitleClickListener(this);

        final RecyclerView recyclerView = root.findViewById(R.id.group_contact_list);
        recyclerView.setLayoutManager(new RichStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        adapter = new GroupContactFragment.GroupListGridAdapter();
        recyclerView.setAdapter(adapter);
        allCall = root.findViewById(R.id.all_call_switch);
        allCall.setChecked(dmrManager.getContactType() == 2);
        allCall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    SharedPreferences.Editor mEditor = mSp.edit();
                    mEditor.putInt("preContact", dmrManager.getTransmitContact());
                    mEditor.putInt("preContactType", dmrManager.getContactType());
                    mEditor.apply();
                    dmrManager.setTransmitContact(16777215);
                    dmrManager.setContactType(2);
                    dmrManager.flush();
                } else {
                    int transmitContact = mSp.getInt("preContact", 1);
                    int callType = mSp.getInt("preContactType", 1);
                    dmrManager.setTransmitContact(transmitContact);
                    dmrManager.setContactType(callType);
                    dmrManager.flush();
                }
                adapter.notifyDataSetChanged();
            }
        });
        return root;
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_left_title:
                getActivity().finish();
                break;
            case R.id.txt_right_title:
                initDialog();
                break;
            default:
                break;
        }
    }

    class GroupListGridAdapter extends RecyclerView.Adapter<GroupContactFragment.GroupListGridAdapter.LinearViewHolder> {
        private String TAG = "rich---GroupListGridAdapter";

        @SuppressLint("WrongConstant")
        private GroupListGridAdapter() {
        }

        @NonNull
        @Override
        public GroupContactFragment.GroupListGridAdapter.LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Log.d(TAG, "onCreateViewHolder");
            return new GroupContactFragment.GroupListGridAdapter.LinearViewHolder(
                    LayoutInflater.from(mContext).inflate(R.layout.item_rv_group_contact_list, parent, false));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final GroupContactFragment.GroupListGridAdapter.LinearViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            Log.d(TAG, "onBindViewHolder");
            if (groupModels.size() == 0) {
                return;
            }
            holder.groupDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dmrManager.getTransmitContact() == groupModels.get(position).getPhone() && dmrManager.getContactType() == 1) {
                        Toast.makeText(mContext, "Current contact can't delete", Toast.LENGTH_SHORT).show();
                    } else {
                        if(groupModels.size() == 1){
                            Toast.makeText(mContext, "You can't delete all your group contacts", Toast.LENGTH_SHORT).show();
                        }else {
                            mDataBaseUtils.deleteContactById(groupModels.get(position).getId());
                            groupModels.clear();
                            groupModels.addAll(mDataBaseUtils.findGroupContact());
                            notifyDataSetChanged();
                        }
                    }
                }
            });

            holder.contactItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dmrManager.setTransmitContact(groupModels.get(position).getPhone());
                    dmrManager.setContactType(1);
                    dmrManager.flush();
                    allCall.setChecked(dmrManager.getContactType() == 2);
                    mSoundPoolUtils.playSound(false);
                    notifyDataSetChanged();
                }
            });

            if (dmrManager.getTransmitContact() == groupModels.get(position).getPhone() && dmrManager.getContactType() == 1) {
                holder.groupName.setTextColor(Color.RED);
            } else {
                holder.groupName.setTextColor(Color.WHITE);
            }

            holder.groupName.setText(groupModels.get(position).getName());
            holder.groupId.setText(groupModels.get(position).getPhone() + "");
        }

        @Override
        public int getItemCount() {
            return groupModels.size();
        }

        public class LinearViewHolder extends RecyclerView.ViewHolder {
            private TextView groupName;
            private TextView groupId;
            private ImageView groupDelete;
            private LinearLayout contactItem;

            private LinearViewHolder(View itemView) {
                super(itemView);
                groupName = itemView.findViewById(R.id.group_name);
                groupId = itemView.findViewById(R.id.group_id);
                groupDelete = itemView.findViewById(R.id.group_delete);
                contactItem = itemView.findViewById(R.id.rv_contact_item_view);
            }
        }

    }

    private void initDialog() {
        final CommonDialog dialog = new CommonDialog(mContext);
        dialog.setNickName("Group")
                .setNickExtId("ID")
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .setTitle("Create Group")
                .setSingle(false).setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                String contactName = dialog.getCommonName().getText().toString();
                String contactNum = dialog.getCommonExtId().getText().toString();
                if (!TextUtils.isEmpty(contactName) && !TextUtils.isEmpty(contactNum)) {
                    if (!ConvertUtils.isNumeric(contactNum)) {
                        Toast.makeText(mContext, "Group contact is not number.", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    int contactVal = Integer.valueOf(contactNum.trim());
                    if (contactVal <= 0 || contactVal > 16776415) {
                        Toast.makeText(mContext, "Group contact invalid.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    int count = mDataBaseUtils.findGroupContact(contactVal);
                    if (count > 0) {
                        Toast.makeText(mContext, "Group contact already exist.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    mDataBaseUtils.insertGroupContact(contactName, contactVal);
                    groupModels.clear();
                    groupModels.addAll(mDataBaseUtils.findGroupContact());
                    adapter.notifyDataSetChanged();
                    Toast.makeText(mContext, "Save success.", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                } else {
                    Toast.makeText(mContext, "data is null.", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onNegativeClick() {
                dialog.dismiss();
                Toast.makeText(mContext, "cancel", Toast.LENGTH_SHORT).show();
            }
        }).show();
    }
}